package com.comp3111.happymeal;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.configuration.Configuration;
import com.configuration.Owner;
import com.controller.MealCommentFetch;
import com.controller.MealFetch;
import com.controller.UserFetch;
import com.controller.UserFollow;
import com.object.Meal;
import com.object.MealComment;
import com.object.User;
import com.user.Helper;

import android.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class UserProfileActivity extends NavigationDrawerActivity {
	private static Button btn_following_btn;
	private static Button btn_edit_profile_btn;
	TextView tv_profile_page_name;
	TextView tv_profile_page_description;
	TextView tv_profile_recent_activity;
	ImageView iv_profile_page_profile_picture;
	//private ListView listView;
    //private SimpleAdapter adapter;
    private ListView userActivityListView;
    private SimpleAdapter userActivityAdapter;
    //private ListView listView3;
    //private SimpleAdapter adapter3;
    private int backButtonCount;
    
    //Constant for displaying listview
    final int NUM_COMMENT = 10;
    
    int user_id;
    
    //For handling the onclick user activity
    private List<Integer> mealIdList;
    private List<Integer> commentIdList;
    
    private String mealPictureDrawableURL;
    private Drawable mealPicture;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_page);
        createDrawer();
        
      //Initialize the back button count
      backButtonCount = 0;
        
        Bundle extras = getIntent().getExtras();
		user_id  = Integer.parseInt(extras.getString("USERID"));
        
		//Fetch data based on user id
		UserFetch userFetch = new UserFetch();
		User user = userFetch.fetchUserById(user_id);
        
		//Link page variable to interface element
		tv_profile_page_name = (TextView) findViewById(R.id.profile_page_name);
		tv_profile_page_description = (TextView) findViewById(R.id.profile_page_description);
		iv_profile_page_profile_picture = (ImageView)findViewById(R.id.profile_page_profile_picture);
		tv_profile_recent_activity = (TextView) findViewById(R.id.profile_page_recent_activity);
		btn_following_btn = (Button) findViewById(R.id.profile_page_following_btn);
        btn_edit_profile_btn = (Button) findViewById(R.id.profile_page_edit_profile_btn);
        

		//Set variables to different view
        String userName = user.getName();
        tv_profile_page_name.setText(userName);
        tv_profile_page_description.setText(user.getDescription());
        if(user.getProfilePicture() != ""){
			iv_profile_page_profile_picture.setTag(Configuration.baseURL + user.getProfilePicture());
			new DownloadImagesForImageView().execute(iv_profile_page_profile_picture);
		}
		
        UserFollow userFollow = new UserFollow();
		boolean isFollowed = userFollow.isFollowingByUserId(user_id);
		if(user_id != Owner.id){
			//Hide edit profile button when viewing other profile
			//btn_edit_profile_btn.setVisibility(View.INVISIBLE);
			if(isFollowed){
				btn_edit_profile_btn.setText("Unfollow");
			}else{
				btn_edit_profile_btn.setText("Follow");
			}
			
		}
        
        btn_following_btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(UserProfileActivity.this, UserProfileFollowingListActivity.class);
				
				//Pass pass intent								
				intent.putExtra("USERID",Integer.toString(user_id).trim());
				
			    startActivity(intent);
			}
		});
        btn_edit_profile_btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if(user_id == Owner.id){
					Intent intent = new Intent(UserProfileActivity.this, UserProfileEditUserProfileActivity.class);
			    	startActivity(intent);
				}else{
					//Follow the user
					UserFollow userFollow = new UserFollow();
					int SUCCESS = 1;
					if(!userFollow.isFollowingByUserId(user_id)){
						if(SUCCESS == userFollow.followUserById(user_id)){
							Toast.makeText(getApplicationContext(), "Successfully follow!", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(getApplicationContext(), "Fail to follow. Please try again!", Toast.LENGTH_SHORT).show();
						}
					}else{
						if(SUCCESS == userFollow.unfollowUserById(user_id)){
							Toast.makeText(getApplicationContext(), "Successfully unfollow!", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(getApplicationContext(), "Fail to unfollow. Please try again!", Toast.LENGTH_SHORT).show();
						}
					}
					
					//Refresh page
                	Intent intent = getIntent();
                    finish();
                    startActivity(intent);
					
				}
			}
		});
        // if followed or the profile page belongs to the user, show recent activities
        if((user_id == Owner.id) || isFollowed)
        {
        	tv_profile_recent_activity.setText("Recent Activities");
        	userActivityListView = (ListView)findViewById(R.id.profile_page_user_activity);
        	if (user_id == Owner.id)
        		userName = "You";
            userActivityAdapter = new SimpleAdapter(this, getUserActivity(userName), R.layout.comment_food_listview,
			new String[]{"comment_food_user_review_pic","comment_food_brief_description","comment_food_time", "comment_food_comments", "comment_food_love_pic"},
			new int[]{R.id.comment_food_user_review_pic, R.id.comment_food_brief_description, R.id.comment_food_time, R.id.comment_food_comments, R.id.comment_food_love_pic});
            userActivityListView.setAdapter(userActivityAdapter);
            userActivityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                //Handle no comment
                if(mealIdList.size()==0) {
                	return;
                }
                int mealId = mealIdList.get(position);
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(UserProfileActivity.this,FoodPageActivity.class);
		    	//Pass pass intent								
		    	intentPass.putExtra("MEALID",Integer.toString(mealId).trim());	
		    	//Go to next page
		    	startActivity(intentPass);
		    	//return false;
                }
            }); 
            userActivityAdapter.setViewBinder(new ViewBinder(){
        	    public boolean setViewValue(View view,Object data,String textRepresentation){
				    if(view instanceof ImageView && data instanceof Drawable) {
					    ImageView iv=(ImageView)view;
					    iv.setImageDrawable((Drawable)data);
					    return true;
				    }
			    	else return false;
			    }
            });
            Helper.setListViewHeightBasedOnChildren(userActivityListView);
        }
  
        
        //Release unused ram
        System.gc();
    }
    
    
    
    private List<Map<String, Object>> getUserActivity(String userName) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		mealIdList = new ArrayList<Integer>();
		commentIdList = new ArrayList<Integer>();
		
		MealCommentFetch mealCommentFetch = new MealCommentFetch();
		List<MealComment> mealCommentList = mealCommentFetch.fetchMealCommentByUserId(user_id);
		UserFetch userFetch = new UserFetch();
		
		if(mealCommentList != null){
			int counter = 0;
			
		    for(MealComment mealComment : mealCommentList){
		    	// Display at most 5 comments
		    	if(counter > NUM_COMMENT-1){
		    		break;
		    	}else{
		    		counter++;
		    	}
							
				//drawableURL = Configuration.baseURL + restaurant.getProfilePicture();
				Map<String, Object> map = new HashMap<String, Object>();
				
				User user = userFetch.fetchUserById(mealComment.getUser());
				
				MealFetch mealFetch = new MealFetch();
				Meal meal = mealFetch.fetchMealById(mealComment.getMeal());
				
				if(user.getProfilePicture()!=null){
					
					mealPictureDrawableURL = Configuration.baseURL + meal.getPicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							mealPicture = loadImageFromURL(mealPictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				
				
				//Display the mealPicture
				map.put("comment_food_user_review_pic", mealPicture);
				//Display the meal name
				map.put("comment_food_brief_description", userName + " commented " + meal.getName());
				map.put("comment_food_comments", mealComment.getComment());
				map.put("comment_food_time", mealComment.getCreateDate());
				
				if(mealCommentFetch.isLikedByUser(meal.getId(),user.getId())){
					map.put("comment_food_love_pic", R.drawable.love);
				}else{
					map.put("comment_food_love_pic", R.drawable.nolove);
				}
				
				list.add(map);
				
				//List containing restaurant id in order
				mealIdList.add(mealComment.getMeal());
				commentIdList.add(mealComment.getId());
	    	}
		    
		    
	    }else{
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("comments","No recent Activity!");
	    	list.add(map);
	    }

		return list;
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
            /*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;
            */
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
    
    /*
    private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_review_pic", R.drawable.profile_pic);
		map.put("brief_description", "You commented a restaurant");
		map.put("time", "29/3/2014 11:28PM");
		map.put("comments", "The restaurant is good. The staff are nice.");
		map.put("user_rating", "Rating: 5/5");
		list.add(map);
		
		return list;
	}
    private List<Map<String, Object>> getData3() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_review_pic", R.drawable.profile_pic);
		map.put("brief_description", "You loved Baby Mac");
		map.put("time", "29/3/2014 11:28PM");
		list.add(map);
		
		return list;
	}
    
    //the app will not allow it to go back to previous Activity through back
  	// Override the back button to quit the app if back is pressed twice

    public void onBackPressed(){
		if(Configuration.showLog){
			Log.d("UserProfilePageActivity", "onBackPressed");
		}
			
        if(backButtonCount >= 1){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else{
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
	}*/
}